﻿using CSRedis;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Org.BouncyCastle.Pkcs;
using System.Collections.Generic;
using System.IO.Pipelines;
using System.Linq;
using System.Runtime.InteropServices;
using System.Xml;
using WorkOne.Domain;
using WorkOne.Domain.Model;
using WorkOne.Domain.Redis;
using WorkOne.Webapi.Extention;
using Yitter.IdGenerator;

namespace WorkOne.Webapi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ShopController : ControllerBase
    {
        private readonly GoodsDbContext db;
        private readonly CSRedisClient redis;
        private readonly RedisClient redisClient;

        public ShopController(GoodsDbContext db, CSRedisClient redis, RedisClient redisClient)
        {
            this.db = db;
            this.redis = redis;
            this.redisClient = redisClient;
        }

        /// <summary>
        /// 购物车显示先读redis有序列表单表再读sqlserver双表
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpGet("GetShopCarSortSql")]
        public IActionResult GetShopCarSortSql(int uid)
        {
            var stringlist = redis.ZRange($"cart:{uid}", 0, -1);

            if (stringlist.Count() == 0)
            {
                var allcar = db.shopcars.Join(db.goodsCarts, a => a.Sid, b => b.Sid, (a, b) => new
                {
                    a,
                    b,
                }).ToList().Where(s => s.a.Uid == uid).ToList();

                var list2 = allcar.Join(db.Goods, a => a.b.Gid, b => b.Id, (a, b) => new
                {
                    a.a.Sid,
                    a.a.Uid,
                    a.a.CartCreateTime,
                    a.b.GoodsNum,
                    b.IsDel,
                    b.Desc,
                    b.State,
                    b.Images,
                    b.Id,
                    b.Name,
                    b.Price,
                    b.GoodsType,
                }).ToList();

                foreach (var item in list2)
                {
                    AddShopCarSortedList(new GoodsCart { Uid = item.Uid, Gid = item.Id, GoodsNum = item.GoodsNum });
                }
                return Ok(list2);
            }
            else
            {
                var list = stringlist.Select(a => JsonConvert.DeserializeObject<Goods>(a));
                list = list.Where(a => a.IsDel == false);
                return Ok(list);
            }
        }

        /// <summary>
        /// 添加购物车有序列表 单表
        /// </summary>
        /// <param name="shopcar"></param>
        /// <returns></returns>
        [HttpPost("AddShopCarSortedList")]
        public IActionResult AddShopCarSortedList(GoodsCart goodscart)
        {
            Goods goods = db.Goods.FirstOrDefault(a => a.Id == goodscart.Gid);
            var cart = redis.ZRangeByScore($"cart:{goodscart.Uid}", goodscart.Gid, goodscart.Gid);

            if (cart.Count() == 0 || cart[0] == null)
            {
                if (goods == null)
                {
                    return Ok(-1);
                }
                goods.GoodsNum = goodscart.GoodsNum;
                var res = redis.ZAdd($"cart:{goodscart.Uid}", (goodscart.Gid, JsonConvert.SerializeObject(goods)));
                return Ok(res);
            }

            Goods goods1 = JsonConvert.DeserializeObject<Goods>(cart[0]);
            goods1.GoodsNum = goodscart.GoodsNum + goods1.GoodsNum;
            redis.ZRemRangeByScore($"cart:{goodscart.Uid}", goodscart.Gid, goodscart.Gid);

            var res2 = redis.ZAdd($"cart:{goodscart.Uid}", (goods1.Id, JsonConvert.SerializeObject(goods1)));

            return Ok(res2);
        }

        /// <summary>
        /// 添加购物车进 redis有序列表单表和sqlserver  sql关系一对一双表
        /// </summary>
        /// <param name="shopcar"></param>
        /// <returns></returns>
        [HttpPost("AddShopCar")]
        public IActionResult AddShopCar(GoodsCart goodscart)
        {
            AddShopCarSortedList(goodscart);
            var tran = db.Database.BeginTransaction(System.Data.IsolationLevel.RepeatableRead);
            try
            {
                var list = db.goodsCarts.Include(a => a.Shopcar).ToList();
                if (list.Count() != 0)
                {
                    list = list.Where(b => b.Shopcar.Uid == goodscart.Uid).ToList();
                    if (list.Count() != 0)
                    {
                        list = list.Where(b => b.Gid == goodscart.Gid).ToList();
                        if (list.Count() != 0)
                        {
                            list[0].GoodsNum += goodscart.GoodsNum;

                            db.goodsCarts.Update(list[0]);
                            int d1 = db.SaveChanges();
                            return Ok(d1);
                        }
                    }
                }

                Shopcar shopcar1 = new Shopcar { Uid = goodscart.Uid, CreateTime = DateTime.Now };
                db.shopcars.Add(shopcar1);
                db.SaveChanges();
                GoodsCart goodsCart = new GoodsCart() { Sid = shopcar1.Sid, Gid = goodscart.Gid, GoodsNum = goodscart.GoodsNum };
                db.goodsCarts.Add(goodsCart);

                int d = db.SaveChanges();
                tran.Commit();
                return Ok(d);
            }
            catch (Exception)
            {
                tran.Rollback();
                throw;
            }

            #region
            //using (var tran = db.Database.BeginTransaction())
            //{
            //    try
            //    {
            //        #region

            //        var list = db.goodsCarts.Include(a => a.Shopcar).ToList();
            //        if (list != null)
            //        {
            //            list = list.Where(b => b.Shopcar.Uid == goodscart.Uid).ToList();
            //        }

            //        if (list == null || list.Count == 0)
            //        {
            //            Shopcar shopcar = new Shopcar()
            //            {
            //                CartCreateTime = DateTime.Now,
            //                CreatePeople = goodscart.Uid.ToString(),
            //                CreateTime = DateTime.Now,
            //                Uid = goodscart.Uid,
            //                UpdatePeople = goodscart.Uid.ToString(),
            //                UpdateTime = DateTime.Now
            //            };
            //            db.shopcars.Add(shopcar);
            //            int a = db.SaveChanges();
            //            if (a > 0)
            //            {
            //                int sid = (int)db.shopcars.FirstOrDefault(a => a.Uid == goodscart.Uid).Sid;
            //                goodscart.Sid = sid;
            //                db.goodsCarts.Add(goodscart);
            //                int f = db.SaveChanges();
            //                tran.Commit();
            //                return Ok(f);
            //            }
            //        }
            //        else
            //        {
            //            int sid = (int)list[0].Sid;
            //            goodscart.Sid = sid;

            //            list = list.Where(a => a.Gid == goodscart.Gid).ToList();
            //            if (list.Count == 0)
            //            {
            //                db.goodsCarts.Add(goodscart);
            //                int e = db.SaveChanges();
            //                tran.Commit();
            //                return Ok(e);
            //            }
            //            else
            //            {
            //                list[0].GoodsNum += goodscart.GoodsNum;

            //                db.goodsCarts.Update(list[0]);
            //                int d = db.SaveChanges();
            //                tran.Commit();
            //                return Ok(d);
            //            }
            //        }
            //        int c = db.SaveChanges();
            //        tran.Commit();
            //        return Ok(c);
            //        #endregion
            //    }
            //    catch (Exception)
            //    {
            //        tran.Rollback();
            //        throw;
            //    }
            //}
            #endregion
        }

        [HttpGet("GetGoodsPager")]
        public IActionResult GetGoodsPager(int pageIndex, int pageSize)
        {
            //先分页，找出分页的商品id
            long strat = (pageIndex - 1) * pageSize;
            long stop = strat + pageSize - 1;
            string[] idlist = redis.ZRange("goodsid", strat, stop);

            //取需要的商品对象
            string[] goodsString = redis.HMGet("goodsinfo", idlist);
            //把商品的字符串形态反序列化为对象形态
            //1.使用Ling
            //2.使用循环
            var query = from g in goodsString
                        select JsonConvert.DeserializeObject<Goods>(g);

            //取总记录数量
            long count = redis.ZCard("goodsid");

            var res = new { total = count, data = query.ToList() };
            return Ok(res);
        }

        [HttpPost("Update")]
        public IActionResult Update()
        {
            string ordercode = Request.Form["out_trade_no"];
            string state = Request.Form["trade_status"];
            if (state == "TRADE_SUCCESS" || state == "TRADE_FINISHED")
            {
                var tran = db.Database.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
                try
                {
                    // 修改订单状态
                    var order = db.orders.FirstOrDefault(a => a.OrderCode == ordercode);
                    lock (order)
                    {
                        order.State = (OrderState)2;
                        db.orders.Update(order);
                    }
                    // 修改商品数量
                    var goodlist = db.orderGoods.Where(a => a.OrderId == order.OrderId).Join(db.Goods, a => a.GId, b => b.Id, (a, b) => new
                    {
                        a,
                        b
                    }).ToList();
                    foreach (var item in goodlist)
                    {
                        Goods good = db.Goods.Find(item.b.Id);
                        lock (good)
                        {
                            good.NumSum -= item.a.BuyCount;
                            db.Goods.Update(good);
                        }
                    }
                    // 删除购物车商品
                    var cart = db.goodsCarts.Join(db.shopcars, a => a.Sid, b => b.Sid, (a, b) => new
                    {
                        a,
                        b
                    }).Where(a => a.b.Uid == order.Uid).ToList();
                    foreach (var item in cart)
                    {
                        foreach (var item1 in goodlist)
                        {
                            if (item.a.Gid == item1.b.Id)
                            {
                                lock (item)
                                {
                                    var a = db.shopcars.Find(item.a.Sid);
                                    db.shopcars.Find(item.a.Sid).IsDel = true;
                                    db.shopcars.Update(a);
                                    var b = db.goodsCarts.FirstOrDefault(a => a.Gid == item1.b.Id);
                                    db.goodsCarts.FirstOrDefault(a => a.Gid == item1.b.Id).IsDel = true;
                                    db.goodsCarts.Update(b);
                                }
                            }
                        }
                    }
                    db.SaveChanges();
                    tran.Commit();
                    return Ok(1);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    return Ok(0);
                }
                #region 购物车
                //var tran = db.Database.BeginTransaction();
                ////修改商品状态
                //var order = db.orders.FirstOrDefault(a => a.OrderCode == ordercode);
                //order.State = (OrderState)2;
                //db.orders.Update(order);
                //db.SaveChanges();
                //var goodlist = db.orderGoods.Where(a => a.OrderId == order.OrderId).Join(db.Goods, a => a.GId, b => b.Id, (a, b) => new
                //{
                //    a,
                //    b
                //}).ToList();
                ////循环修改商品数量
                //foreach (var item in goodlist)
                //{
                //    Goods good = db.Goods.Find(item.b.Id);
                //    good.NumSum -= item.a.BuyCount;
                //    db.Goods.Update(good);
                //    db.SaveChanges();
                //}
                ////循环删除购物商品
                //var cart = db.goodsCarts.Join(db.shopcars, a => a.Sid, b => b.Sid, (a, b) => new
                //{
                //    a,
                //    b
                //}).Where(a => a.b.Uid == order.Uid).ToList();

                //foreach (var item in cart)
                //{
                //    foreach (var item1 in goodlist)
                //    {
                //        if (item.a.Gid == item1.b.Id)
                //        {
                //            db.shopcars.Remove(db.shopcars.Find(item.a.Sid));
                //            db.goodsCarts.Remove(db.goodsCarts.FirstOrDefault(a => a.Gid == item1.b.Id));
                //            db.SaveChanges();
                //        }
                //    }
                //}

                //tran.Commit();
                //return Ok(1);
                #endregion 购物车
            }
            else
            {
                var order = db.orders.FirstOrDefault(a => a.OrderCode == "ordercode");
                order.State = (OrderState)6;
                db.orders.Update(order);
                db.SaveChanges();
                return Ok(0);
            }

            //修改订单状态为成功或失败
            //如果订单成功修改商品的库存量,
            //如果订单成功,在购物车中删除对应商品
            return Ok("调用此方法,根据订单编号,修改订单状态为已支付");
        }

        /// <summary>
        /// 包含日期条件
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="date1">开始日期</param>
        /// <param name="date2">结束日期</param>
        /// <returns></returns>
        [HttpGet("GetGoodsDatePager")]
        public IActionResult GetGoodsDatePager(int pageIndex, int pageSize, DateTime? date1, DateTime? date2)
        {
            //先分页，找出分页的商品id
            long strat = (pageIndex - 1) * pageSize;

            decimal max = Convert.ToDecimal(date2.Value.ToString("yyyyMMdd"));
            decimal min = Convert.ToDecimal(date1.Value.ToString("yyyyMMdd"));

            string[] idlist = redis.ZRevRangeByScore("goodsid", max, min, pageSize, strat);

            //取需要的商品对象
            string[] goodsString = redis.HMGet("goodsinfo", idlist);
            //把商品的字符串形态反序列化为对象形态
            //1.使用Ling
            //2.使用循环
            var query = from g in goodsString
                        select JsonConvert.DeserializeObject<Goods>(g);

            //取总记录数量
            long count = redis.ZCount("goodsid", min, max);

            var res = new { total = count, data = query.ToList() };
            return Ok(res);
        }

        /// <summary>
        /// 所有商品进redis库
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("AllGoodsInsertRedisHash")]
        public IActionResult AllGoodsInsertRedisHash()
        {
            //var redisclient = RedisHelpers.Redisclient;
            //var redis = RedisHelpers.Redis;
            var list = db.Goods.ToList();
            int hcount = 0;
            int zcount = 0;
            foreach (var item in list)
            {
                string yitter = YitIdHelper.NextId().ToString();
                if (redis.HSet(RedisKey.Goods, yitter, JsonConvert.SerializeObject(item)))
                {
                    hcount++;
                }
                if (redis.ZAdd(RedisKey.SortGoods, (1, yitter)) >= 0)
                {
                    zcount++;
                }
            }
            //redisclient.Save();
            return Ok(hcount);
        }

        /// <summary>
        /// 获取商品从数据库
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="board"></param>
        /// <param name="type"></param>
        /// <param name="orderby"></param>
        /// <param name="max"></param>
        /// <param name="min"></param>
        /// <returns></returns>
        [HttpGet("GetGoodsListHa")]
        public IActionResult GetGoodsListHa(int pageIndex, int pageSize, int board, string? type, int orderby, decimal max, decimal min)
        {
            var list = db.Goods.ToList();
            int totalCount = list.Count();
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            if (type!="全部")
            {
                list = list.Where(a => a.GoodsType == type).ToList();
            }
            if (max != 0)
            {
                list = list.Where(a => a.Price < max).ToList();
            }
            if (min != 0)
            {
                list = list.Where(a => a.Price > min).ToList();
            }
            if (orderby == 1)
            {
                list = list.OrderByDescending(a => a.Id).ToList();
            }
            return Ok(new
            {
                list = list
            });
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet("HashSortGoodPage")]
        public IActionResult HashSortGoodPage(int pageIndex, int pageSize, int board, string? type, int orderby, decimal max, decimal min)
        {
            //var redisclient = RedisHelpers.Redisclient;
            //var redis = RedisHelpers.Redis;
            long pageCount = 0;
            long totalCount = 0;
            totalCount = redis.ZCard(RedisKey.SortGoods);
            pageCount = (int)Math.Ceiling(totalCount * 1.0 / pageSize);
            long start = (pageIndex - 1) * pageSize;
            long stop = start + pageSize - 1;
            var list = redis.ZRange(RedisKey.SortGoods, start, stop);
            List<Goods> goods = new List<Goods>();
            foreach (var item in list)
            {
                var goodstring = redis.HGet(RedisKey.Goods, item.ToString());
                goods.Add(JsonConvert.DeserializeObject<Goods>(goodstring));
            }

            return Ok(new { pageCount, totalCount, list = goods });
        }

        /// <summary>
        /// 购物车显示sqlserver 关系一对多
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpGet("GetShopCar")]
        public IActionResult GetShopCar(int uid)
        {
            var list = db.goodsCarts.Include(m => m.Shopcar).ToList();
            list = list.Where(c => c.Shopcar.Uid == uid).ToList();
            var list2 = list.Join(db.Goods, a => a.Gid, b => b.Id, (a, b) => new
            {
                a.Shopcar.Sid,
                a.Shopcar.Uid,
                a.Shopcar.CartCreateTime,
                a.GoodsNum,
                b.IsDel,
                b.Desc,
                b.State,
                b.Images,
                b.Id,
                b.Name,
                b.Price,
                b.GoodsType,
            }).ToList();

            return Ok(list2);
        }

        /// <summary>
        /// 添加购物车进hash单表
        /// </summary>
        /// <param name="goodscart"></param>
        /// <returns></returns>
        [HttpPost("AddShopCarHashOne")]
        public IActionResult AddShopCarHashOne(GoodsCart goodscart)
        {
            bool a = false;
            var cart = redis.HGet($"hcart:{goodscart.Uid}", goodscart.Gid.ToString());
            if (cart == null)
            {
                a = redis.HSet($"hcart:{goodscart.Uid}", goodscart.Gid.ToString(), goodscart.GoodsNum);
            }
            else
            {
                goodscart.GoodsNum = int.Parse(cart) + goodscart.GoodsNum;
                a = redis.HSet($"hcart:{goodscart.Uid}", goodscart.Gid.ToString(), goodscart.GoodsNum);
            }
            return Ok(a);
        }

        /// <summary>
        /// 删除购物车
        /// </summary>
        /// <param name="shopcar"></param>
        /// <returns></returns>
        [HttpGet("DeleteShopCar")]
        public IActionResult DeleteShopCar(int uid, int gid)
        {
            long a = redis.ZRemRangeByScore($"cart:{uid}", gid, gid);

            var allcar = db.shopcars.Join(db.goodsCarts, a => a.Sid, b => b.Sid, (a, b) => new
            {
                a,
                b,
            }).FirstOrDefault(s => s.a.Uid == uid && s.b.Gid == gid);
            db.goodsCarts.Remove(db.goodsCarts.Find(allcar.b.GCid));
            db.shopcars.Remove(db.shopcars.Find(allcar.a.Sid));
            long b = db.SaveChanges();

            return Ok(a + b);
        }

        #region 添加购物车进Hash添加双表一对一

        /// <summary>
        /// 添加购物车进Hash添加双表一对一
        /// </summary>
        /// <param name = "shopcar" ></ param >
        /// < returns ></ returns >
        [HttpPost("AddShopCarHash")]
        public IActionResult AddShopCarHash(GoodsCart goodscart)
        {
            var shopcars = redis.HGetAll<Shopcar>(RedisKey.ShopCart)
                ?.Select(v => new Shopcar
                {
                    Sid = v.Value.Sid,
                    Uid = v.Value.Uid,
                    CartCreateTime = v.Value.CartCreateTime
                })?.ToList();

            var goodsCarts = redis.HGetAll<GoodsCart>(RedisKey.GoodsCart)
                 ?.Select(v => new GoodsCart
                 {
                     Gid = v.Value.Gid,
                     Sid = v.Value.Sid,
                     GoodsNum = v.Value.GoodsNum
                 })?.ToList();

            if (shopcars.Count == 0 || goodsCarts.Count == 0)
            {
                if (shopcars != null && goodsCarts == null)
                {
                    redis.HDel(RedisKey.ShopCart);
                    redis.HDel(RedisKey.GoodsCart);
                }
                var yield = YitIdHelper.NextId();
                var shopcar = new Shopcar() { Sid = yield, Uid = goodscart.Uid };
                var goodsCart = new GoodsCart() { Sid = yield, GoodsNum = goodscart.GoodsNum, Gid = goodscart.Gid };
                redis.HSet(RedisKey.ShopCart, yield.ToString(), shopcar);
                redis.HSet(RedisKey.GoodsCart, yield.ToString(), goodsCart);
                return Ok(1);
            }

            var allcar = shopcars.Join(goodsCarts, a => a.Sid, b => b.Sid, (a, b) => new
            {
                a,
                b,
            }).Where(s => s.a.Uid == goodscart.Uid);

            if (allcar == null)
            {
                var yield = YitIdHelper.NextId();
                var shopcar = new Shopcar() { Sid = yield, Uid = goodscart.Uid };
                var goodsCart = new GoodsCart() { Sid = yield, GoodsNum = goodscart.GoodsNum, Gid = goodscart.Gid };
                redis.HSet(RedisKey.ShopCart, yield.ToString(), shopcar);
                redis.HSet(RedisKey.GoodsCart, yield.ToString(), goodsCart);
                return Ok(1);
            }
            else
            {
                var usercart = allcar.FirstOrDefault(s => s.b.Gid == goodscart.Gid);
                if (usercart == null)
                {
                    var yield = YitIdHelper.NextId();
                    var shopcar = new Shopcar() { Sid = yield, Uid = goodscart.Uid };
                    var goodsCart = new GoodsCart() { Sid = yield, GoodsNum = goodscart.GoodsNum, Gid = goodscart.Gid };
                    redis.HSet(RedisKey.ShopCart, yield.ToString(), shopcar);
                    redis.HSet(RedisKey.GoodsCart, yield.ToString(), goodsCart);
                    return Ok(1);
                }
                else
                {
                    var yield = usercart.a.Sid.ToString();
                    var shopcar = new Shopcar() { Sid = Int64.Parse(yield), Uid = goodscart.Uid };
                    var goodsCart = new GoodsCart() { Sid = Int64.Parse(yield), GoodsNum = usercart.b.GoodsNum + goodscart.GoodsNum, Gid = goodscart.Gid };
                    redis.HSet(RedisKey.ShopCart, yield.ToString(), shopcar);
                    redis.HSet(RedisKey.GoodsCart, yield.ToString(), goodsCart);
                    return Ok(1);
                }
            }
        }

        #endregion

        /// <summary>
        /// 从redis双表读取购物车
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        [HttpGet("GetShopCarByHash")]
        public IActionResult GetShopCarByHash(int uid)
        {
            var shopcars = redis.HGetAll<Shopcar>(RedisKey.ShopCart)
                .Select(v => new Shopcar { Sid = v.Value.Sid, Uid = v.Value.Uid, CartCreateTime = v.Value.CartCreateTime }).ToList();

            var goodsCarts = redis.HGetAll<GoodsCart>(RedisKey.GoodsCart)
                 .Select(v => new GoodsCart { Gid = v.Value.Gid, Sid = v.Value.Sid, GoodsNum = v.Value.GoodsNum }).ToList();

            if (shopcars == null || goodsCarts == null)
            {
                return null;
            }
            var allcar = shopcars.Join(goodsCarts, a => a.Sid, b => b.Sid, (a, b) => new
            {
                a,
                b,
            }).Where(s => s.a.Uid == uid);
            if (allcar == null)
            {
                return null;
            }
            var list2 = allcar.Join(db.Goods, a => a.b.Gid, b => b.Id, (a, b) => new
            {
                a.a.Sid,
                a.b.Uid,
                a.a.CartCreateTime,
                a.b.GoodsNum,
                b.IsDel,
                b.Desc,
                b.State,
                b.Images,
                b.Id,
                b.Name,
                b.Price,
                b.GoodsType,
            }).ToList();

            return Ok(list2);
        }

        /// <summary>
        /// 添加购物车进sqlserver双表 一对多
        /// </summary>
        /// <param name="shopcar"></param>
        /// <returns></returns>
        [HttpPost("AddShopCarTwo")]
        public IActionResult AddShopCarTwo(GoodsCart goodscart)
        {
            #region

            var list = db.goodsCarts.Include(a => a.Shopcar).ToList();
            if (list != null)
            {
                list = list.Where(b => b.Shopcar.Uid == goodscart.Uid).ToList();
            }

            if (list == null || list.Count == 0)
            {
                Shopcar shopcar = new Shopcar()
                {
                    CartCreateTime = DateTime.Now,
                    CreatePeople = goodscart.Uid.ToString(),
                    CreateTime = DateTime.Now,
                    Uid = goodscart.Uid,
                    UpdatePeople = goodscart.Uid.ToString(),
                    UpdateTime = DateTime.Now
                };
                db.shopcars.Add(shopcar);
                int a = db.SaveChanges();
                if (a > 0)
                {
                    long sid = db.shopcars.FirstOrDefault(a => a.Uid == goodscart.Uid).Sid;
                    goodscart.Sid = sid;
                    db.goodsCarts.Add(goodscart);
                    return Ok(db.SaveChanges());
                }
            }
            else
            {
                long sid = list[0].Sid;
                goodscart.Sid = sid;

                list = list.Where(a => a.Gid == goodscart.Gid).ToList();
                if (list.Count == 0)
                {
                    db.goodsCarts.Add(goodscart);
                    return Ok(db.SaveChanges());
                }
                else
                {
                    list[0].GoodsNum += goodscart.GoodsNum;

                    db.goodsCarts.Update(list[0]);
                    return Ok(db.SaveChanges());
                }
            }

            return Ok(db.SaveChanges());

            #endregion
        }
    }
}